<template>
  <div class="w-[97%] p-[20px] bg-[white] h-[100%] flex flex-col items-center">
    <div
      class="bg-[url('@/assets/svg/file.png')] bg-cover bg-no-repeat w-[100%] h-[100px] rounded-[10px]"
    >
      <div
        class="text-white font-bold text-[22px] transform translate-x-[150px] translate-y-[10px]"
      >
        {{ Enum.title }}
      </div>
      <div
        class="text-white text-[#888AAB] text-[14px] translate-x-[150px] translate-y-[15px]"
      >
        {{ Enum.tcontent }}
      </div>
    </div>

    <el-upload
      class="w-[80%] h-[calc(100%-400px)] p-[20px] bg-[#fafaff] rounded-[10px] mt-[20px] border-[1px] border-[#bccafb] border-dashed flex justify-center items-center"
      action=""
      :auto-upload="false"
      :on-change="handleFileChange"
      :limit="1"
      drag
      v-model:file-list="fileList"
      accept=".doc,.docx"
    >
      <div class="relative flex" style="width: 100%; height: 100%">
        <img
          src="@/assets/svg/fileUpload.png"
          alt="file"
          class="w-[120px] h-[120px] rounded-[10px]"
        />
        <div class="flex flex-col" v-if="fileList.length === 0">
          <div class="flex text-[20px] mt-[35px] ml-[10px]">
            <div class="text-[blue] cursor-pointer">点击</div>
            <div>或将文件拖拽到这里上传</div>
          </div>
          <div class="text-[14px] text-[#999999] ml-[10px] mt-[5px]">
            {{ Enum.gcontent }}
          </div>
        </div>
        <div class="flex flex-col" v-else>
          <div class="text-[20px] mt-[40px] ml-[10px] mb-[5px]">
            {{ fileList[0].name }}
          </div>
          <div
            class="text-[14px] text-[#999999] mt-[5px] text-left ml-[10px] flex"
          >
            <div>{{ Math.ceil(fileList[0].size / 1000) }}KB</div>
            <el-icon class="ml-[10px] text-[16px] mt-[-1px]"
              ><Close @click.stop="fileList = []"
            /></el-icon>
          </div>
        </div>
      </div>
    </el-upload>

    <el-progress
      class="w-[80%] mt-[40px]"
      :percentage="uploadProgress"
      color="#6f7ad3"
      v-if="uploadFlag"
    />

    <div
      class="text-[#888AAB] mt-[100px] flex flex-col justify-center items-center"
    >
      <el-button type="primary" @click="handleFile">开始查重</el-button>
      <div class="mt-[10px]">{{ Enum.bcontent }}</div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router";
import Enum from "./enum.js";
import { ElMessage } from "element-plus";
import { ref } from "vue";
import { submitTask } from "@/api/know.js";
import { Close } from "@element-plus/icons-vue";

const router = useRouter();
const uploadProgress = ref(0);
const uploadFlag = ref(false);
const fileList = ref([]);

function handleFileChange(file) {
  const isLt50M = file.size / 1024 / 1024 < 50;
  if (!isLt50M) {
    ElMessage.error("文件大小不能超过 50M");
    fileList.value = [];
    return false;
  }
  return true;
}

const handleFile = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning("请上传文件");
    return;
  }

  const fileInfo = fileList.value[0];
  if (!fileInfo.raw) {
    ElMessage.error("文件格式错误，无法获取文件流");
    return;
  }

  uploadFlag.value = true;
  uploadProgress.value = 0;
  let progressInterval = null;
  let isCompleted = false; // 标记接口是否已完成

  // 计算8秒内从0到99%的进度增量（每100ms更新一次）
  const totalSteps = 200; // 20秒 = 80个100ms
  const stepIncrement = 99 / totalSteps;
  let currentStep = 0;

  // 启动进度条定时器
  progressInterval = setInterval(() => {
    if (currentStep < totalSteps && !isCompleted) {
      currentStep++;
      uploadProgress.value = Math.min(
        Math.round(currentStep * stepIncrement),
        99
      );
    }
  }, 100); // 每100ms更新一次进度

  // 调用接口
  submitTask({ file: fileInfo })
    .then((res) => {
      if (res.code == 500) {
        uploadFlag.value = false;
        isCompleted = true;
        ElMessage.error("上传文件失败，请重新上传");
        return;
      }
      isCompleted = true;
      uploadProgress.value = 100; // 接口成功立即到100%
      ElMessage.success("文件上传成功");
      setTimeout(() => {
        uploadFlag.value = false;
        router.push({ name: "fileEnd", query: { fileId: res.data.fileId } });
      }, 300); // 留点时间展示100%状态
    })
    .catch(() => {
      isCompleted = true;
      ElMessage.error("文件上传失败");
      uploadFlag.value = false;
    })
    .finally(() => {
      clearInterval(progressInterval); // 无论成功失败都清除定时器
    });
};
</script>

<style scoped>
/* 隐藏文件列表 */
:deep(.el-upload-list) {
  display: none;
}
</style>
